<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="redis," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="位图BitMapBitmap是一串二进制数，可以利用每一位的位置上数值的0、1来判断该位置上是否存在。并且在BitMap上可执行 AND、OR、XOR等位操作。 SETBITAPISETBIT key offset value Redis中SETBIT就是位图的实现。其中key的值通过二进制进行存储。offset可以设置该二进制的对应的偏移量位上的值为value（0,1）。  value限制，va">
<meta name="keywords" content="redis">
<meta property="og:type" content="article">
<meta property="og:title" content="redis—setbit和bitcount">
<meta property="og:url" content="https://gitee.com/shuhao/2018/04/16/redis—setbit和bitcount/index.html">
<meta property="og:site_name" content="Niki">
<meta property="og:description" content="位图BitMapBitmap是一串二进制数，可以利用每一位的位置上数值的0、1来判断该位置上是否存在。并且在BitMap上可执行 AND、OR、XOR等位操作。 SETBITAPISETBIT key offset value Redis中SETBIT就是位图的实现。其中key的值通过二进制进行存储。offset可以设置该二进制的对应的偏移量位上的值为value（0,1）。  value限制，va">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-04-16T07:21:56.494Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="redis—setbit和bitcount">
<meta name="twitter:description" content="位图BitMapBitmap是一串二进制数，可以利用每一位的位置上数值的0、1来判断该位置上是否存在。并且在BitMap上可执行 AND、OR、XOR等位操作。 SETBITAPISETBIT key offset value Redis中SETBIT就是位图的实现。其中key的值通过二进制进行存储。offset可以设置该二进制的对应的偏移量位上的值为value（0,1）。  value限制，va">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/shuhao/2018/04/16/redis—setbit和bitcount/"/>





  <title> redis—setbit和bitcount | Niki </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cb9f0585e406f878cb2f29c89ad3cdb7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Niki</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天道酬勤</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-categories"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/shuhao/blog/2018/04/16/redis—setbit和bitcount/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Fang ShuHao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Niki">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                redis—setbit和bitcount
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-16T10:10:49+08:00">
                2018-04-16
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/redis/" itemprop="url" rel="index">
                    <span itemprop="name">redis</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="位图BitMap"><a href="#位图BitMap" class="headerlink" title="位图BitMap"></a>位图BitMap</h2><p>Bitmap是一串二进制数，可以利用每一位的位置上数值的0、1来判断该位置上是否存在。并且在BitMap上可执行 AND、OR、XOR等位操作。</p>
<h2 id="SETBIT"><a href="#SETBIT" class="headerlink" title="SETBIT"></a>SETBIT</h2><h4 id="API"><a href="#API" class="headerlink" title="API"></a>API</h4><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">SETBIT key offset value</span><br></pre></td></tr></table></figure>
<p>Redis中SETBIT就是位图的实现。其中key的值通过二进制进行存储。offset可以设置该二进制的对应的偏移量位上的值为value（0,1）。</p>
<ol>
<li><p>value限制，<br>value值必须为0或1；如果是其他值，则又如下错误信息：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">(error) ERR bit is not an integer or out of range</span><br></pre></td></tr></table></figure>
</li>
<li><p>offset限制<br>offset 参数必须大于或等于0 ，小于2^32（bit映射被限制在512M之内）<br>offset 的计数从左往右，也就是说从高位开始计算</p>
</li>
</ol>
<h4 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h4><p>我们将第0位设为1<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt; SETBIT fsh_demo 0 1</span><br><span class="line">(integer) 0</span><br><span class="line"></span><br><span class="line">&gt; get fsh_demo</span><br><span class="line">&quot;\x80&quot;</span><br><span class="line"></span><br><span class="line">&gt; bitcount fsh_demo</span><br><span class="line">(integer) 1</span><br></pre></td></tr></table></figure></p>
<p>将fsh_demo的第0位设为1，通过get返回的是该byte流表示的字符。可以看出1表示的字符为\x80。bitcount则计算总共有多少位数值为1。</p>
<p>我们知道字符“a”的ascII为97，97的二进制位表示为：01100001，我们通过bitset看是否能get到字符“a”<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">172.20.10.73:8080&gt; SETBIT fsh_a 0 0</span><br><span class="line">(integer) 0</span><br><span class="line">172.20.10.73:8080&gt; SETBIT fsh_a 1 1</span><br><span class="line">(integer) 0</span><br><span class="line">172.20.10.73:8080&gt; SETBIT fsh_a 2 1</span><br><span class="line">(integer) 0</span><br><span class="line">172.20.10.73:8080&gt; SETBIT fsh_a 3 0</span><br><span class="line">(integer) 0</span><br><span class="line">172.20.10.73:8080&gt; SETBIT fsh_a 4 0</span><br><span class="line">(integer) 0</span><br><span class="line">172.20.10.73:8080&gt; SETBIT fsh_a 5 0</span><br><span class="line">(integer) 0</span><br><span class="line">172.20.10.73:8080&gt; SETBIT fsh_a 6 0</span><br><span class="line">(integer) 0</span><br><span class="line">172.20.10.73:8080&gt; SETBIT fsh_a 7 1</span><br><span class="line">(integer) 0</span><br><span class="line">172.20.10.73:8080&gt; get fsh_a</span><br><span class="line">&quot;a&quot;</span><br><span class="line">172.20.10.73:8080&gt; BITCOUNT fsh_a</span><br><span class="line">(integer) 3</span><br></pre></td></tr></table></figure></p>
<p>注意一点：offset从左往右开始计算，跟我们二进制计算时从右往左不同。</p>
<h2 id="BITCOUNT"><a href="#BITCOUNT" class="headerlink" title="BITCOUNT"></a>BITCOUNT</h2><p>计算key中值为1的有多少位</p>
<h2 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h2><ul>
<li>统计在线用户<br>因为offset的最大值为2^32，所以我们可以统计最多4294967296用户的在线情况</li>
</ul>
<ol>
<li>我们根据用户id，映射到bitmap中对应的位上</li>
<li>如果用户在线，则将该位数值设为1</li>
<li>使用bitcount统计有多少位值为1，计算出在线用户有多少</li>
</ol>
<ul>
<li>利用位操作对数据分析<br>我们可以用bitmap保存每天的用户打卡数据；假设公司只有八位员<br>11111111<br>01110111<br>我们可以通过 &amp; 操作，来查看没有全部打卡的用户。通过|操作来查看至少打卡一天的用户</li>
</ul>
<h2 id="总结："><a href="#总结：" class="headerlink" title="总结："></a>总结：</h2><p>redis的SETBIT就是对位图的实现封装。并且可以通过位图的 AND OR XOR操作实现统计操作</p>
<blockquote>
<blockquote>
<p>参考<br><a href="https://www.zhihu.com/question/27672245" target="_blank" rel="external">redis的setbit这个bit怎么理解，配合bitcount使用</a><br><a href="https://blog.csdn.net/lglgsy456/article/details/39394961" target="_blank" rel="external">redis 用setbit(bitmap)统计活跃用户</a></p>
</blockquote>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/redis/" rel="tag"># redis</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/04/11/Java实现热部署/" rel="next" title="Java实现热部署">
                <i class="fa fa-chevron-left"></i> Java实现热部署
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/04/16/Mysql优化/" rel="prev" title="Mysql优化">
                Mysql优化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNjY5NS8xMzIzMA=="></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/head.jpg"
               alt="Fang ShuHao" />
          <p class="site-author-name" itemprop="name">Fang ShuHao</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">135</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories">
                <span class="site-state-item-count">35</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">93</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#位图BitMap"><span class="nav-number">1.</span> <span class="nav-text">位图BitMap</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SETBIT"><span class="nav-number">2.</span> <span class="nav-text">SETBIT</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#API"><span class="nav-number">2.0.1.</span> <span class="nav-text">API</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#示例"><span class="nav-number">2.0.2.</span> <span class="nav-text">示例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#BITCOUNT"><span class="nav-number">3.</span> <span class="nav-text">BITCOUNT</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#应用场景"><span class="nav-number">4.</span> <span class="nav-text">应用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结："><span class="nav-number">5.</span> <span class="nav-text">总结：</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fang ShuHao</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  



  
  

  

  

  

  


  

</body>
</html>
